<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="医生名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['doctorName',{rules: [{
          required: true,
          message: '请输入医生名称!',
          }]}]" placeholder="请输入医生名称"></a-input>
        </a-form-item>
        <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select v-decorator="['sex',{rules: [{
          required: true,
          message: '请选择性别!',
          }]}]"
                    placeholder="请选择性别">
            <a-select-option :value="1">男</a-select-option>
            <a-select-option :value="2">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="置顶" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group name="radioGroup" :default-value="0"
                         v-decorator="['isTop',{rules: [{ required: true, message: '请选择是否置顶!', }]}]"
                         placeholder="请选择是否置顶">
            <a-radio :value="0">
              否
            </a-radio>
            <a-radio :value="1">
              是
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="医生头像" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <demo-upload v-model="model.doctorAvatar"></demo-upload>
        </a-form-item>
        <a-form-item label="医生职位" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['doctorPosition',{rules: [{
          required: true,
          message: '请输入医生职位!',
          }]}]" placeholder="请输入医生职位"></a-input>
        </a-form-item>
        <a-form-item label="所属医院" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            show-search
            v-decorator="['hospitalId',{rules: [{ required: true,  message: '请选择所属医院!', }]}]"
            placeholder="所属医院"
            style="width: 100%"
            :filter-option="filterOption"
            @popupScroll="handlePopupScroll"
            @search="handleSearch">
            <a-select-option v-for="a in hospitalTwoList" :key="a.id" :value="a.id">
              {{ a.hospitalName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属科室" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select v-decorator="['departmentId',{rules: [{  required: true, message: '请选择所属医院!', }]}]"
                    placeholder="请选择所属科室">
            <a-select-option v-for="d in departmentList"
                             :key="d.id"
                             :value="d.id">{{ d.departmentName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="专业擅长" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['specialty',{rules: [{required: true, message: '请输入专业擅长!', }]}]"
                   placeholder="请输入专业擅长"></a-input>
        </a-form-item>
        <a-form-item label="学历" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['education',{}]" placeholder="请输入学历"></a-input>
        </a-form-item>
        <a-form-item label="门诊时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['outpatientTime',{}]" placeholder="请输入门诊时间"></a-input>
        </a-form-item>
        <a-form-item label="医生标签" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <template v-for="(tag, index) in tags">
            <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
              <a-tag :key="tag.id" :closable="index !== 0" @close="() => handleClose(tag)">
                {{ `${tag.slice(0, 20)}...` }}
              </a-tag>
            </a-tooltip>
            <a-tag v-else :key="tag.id" :closable="index !== 0" @close="() => handleClose(tag)">
              {{ tag.tag }}
            </a-tag>
          </template>
          <a-input
            v-if="inputVisible"
            ref="input"
            type="text"
            size="small"
            :style="{ width: '78px' }"
            :value="inputValue"
            @change="handleInputChange"
            @blur="handleInputConfirm"
            @keyup.enter="handleInputConfirm"
          />
          <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput">
            <a-icon type="plus"/>
            添加标签
          </a-tag>
        </a-form-item>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>

  import {getAction, httpAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import {validateDuplicateValue} from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import DemoUpload from '@/components/jeecg/DemoUpload'


  export default {
    name: "MedicalDoctorInfoModal",
    components: {
      JDate,
      DemoUpload
    },
    data() {
      return {
        form: this.$form.createForm(this),
        title: "操作",
        width: 800,
        visible: false,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        validatorRules: {},
        url: {
          add: "/hospital/medicalDoctorInfo/add",
          edit: "/hospital/medicalDoctorInfo/edit",
          getDepartmentList: "/hospital/medicalDepartmentInfo/getNodeDepartment",
          getHospitalList: "/hospital/medicalHospitalInfo/getList",
        },
        hospitalList: [],
        hospitalTwoList: [],
        allDataZ: [],
        departmentList: [],
        tags: [],
        inputVisible: false,
        inputValue: '',
        valueData: '',
        treePageSize: 100,
        scrollPage: 1
      }
    },
    created() {
    },
    mounted() {
      this.initIndex();
    },
    methods: {
      initIndex() {
        getAction(this.url.getDepartmentList, {departmentGrade: 1}).then((res) => {
          if (res.success) {
            this.departmentList = res.result;
          }
        });
        getAction(this.url.getHospitalList).then((res) => {
          if (res.success) {
            this.hospitalList = res.result;
            this.hospitalTwoList = res.result.slice(0, 100);
          }
        });
      },
      add() {
        this.edit({});
      },
      edit(record) {
        this.tags = [];
        this.form.resetFields();
        if (!record.isTop) {
          record.isTop = 0;
        }
        if (record.hospitalId) {
          this.selectHospitalList(record.hospitalName);
        }
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'doctorName', 'isTop', 'doctorAvatar', 'doctorPosition', 'hospitalId', 'departmentId', 'specialty', 'createBy', 'createTime', 'updateBy', 'updateTime', 'delFlag', 'doctorLabels', 'sex', 'education', 'outpatientTime'))
        })
        if (this.model.doctorLabels != null) {
          this.tags = this.model.doctorLabels;
        }
      },
      close() {
        this.$emit('close');
        this.visible = false;
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            this.model.doctorLabels = this.tags;
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据", formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }

        })
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'doctorName', 'isTop', 'doctorAvatar', 'doctorPosition', 'hospitalId', 'departmentId', 'specialty', 'createBy', 'createTime', 'updateBy', 'updateTime', 'delFlag', 'sex', 'education', 'outpatientTime'))
      },
      showInput() {
        this.inputVisible = true;
        this.$nextTick(function () {
          this.$refs.input.focus();
        });
      },
      handleInputChange(e) {
        this.inputValue = e.target.value;
      },
      handleInputConfirm() {
        const inputValue = this.inputValue;
        let tags = this.tags;
        if (inputValue && tags.indexOf(inputValue) === -1) {
          tags = [...tags, {tag: inputValue}];
        }
        Object.assign(this, {
          tags,
          inputVisible: false,
          inputValue: '',
        });
      },
      selectHospitalList(value) {
        let param = {hospitalName: value};
        //通过接口获取数据
        getAction(this.url.getHospitalList, param).then((res) => {
          if (res.success) {
            let newList = res.result;
            if (newList.length > 100) {
              this.hospitalTwoList = res.result;
            } else {
              this.hospitalTwoList = res.result;
              this.hospitalList.forEach(item => {
                if (item.hospitalName.indexOf(value) < 0 && this.hospitalTwoList.length < 100) {
                  this.hospitalTwoList.push(item);
                }
              });
            }
            console.info("result:{}", res.result)
          }
        });
      },
      handleSearch(value) {
        console.info("打印value：{}", value);
        this.valueData = value;
        let newList = [];
        if (value) {
          //有值搜索时进行for循环
          this.hospitalList.forEach(item => {
            if (item.hospitalName.indexOf(value) >= 0) {
              newList.push(item);
            }
          });
          this.hospitalTwoList = newList;
        } else {
          //没有值时进行第一页截取
          this.hospitalTwoList = [];
          this.scrollPage = 1;
          this.hospitalTwoList = this.hospitalList.slice(0, 100);
        }
      },
      handlePopupScroll(e) {
        //下拉框下滑事件
        const {target} = e;
        const scrollHeight = target.scrollHeight - target.scrollTop;
        const clientHeight = target.clientHeight;
        // 下拉框不下拉的时候
        if (scrollHeight === 0 && clientHeight === 0) {
          this.scrollPage = 1;
          console.log(this.scrollPage);
        } else {
          // 当下拉框滚动条到达底部的时候
          if (scrollHeight < clientHeight + 5) {
            this.scrollPage = this.scrollPage + 1;
            const scrollPage = this.scrollPage;// 获取当前页
            const treePageSize = this.treePageSize * (scrollPage || 1);// 新增数据量
            const newData = [];// 存储新增数据
            let max = ''; // max 为能展示的数据的最大条数
            if (this.hospitalList.length > treePageSize) {
              // 如果总数据的条数大于需要展示的数据
              max = treePageSize;
            } else {
              // 否则
              max = this.hospitalList.length;
            }
            //判断是否有搜索，带了搜索走搜索的方法如果下拉不进行操作
            console.info("valueData:{}", this.valueData)
            if (!this.valueData) {
              this.hospitalList.forEach((item, index) => {
                if (index < max) { // 当data数组的下标小于max时
                  newData.push(item);
                }
              })
              //将新增的数据赋值到要显示的数组中
              this.hospitalTwoList = newData;
            }
          }
        }
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
    }
  }
</script>